<?php

namespace app\api\controller;

use addons\third\library\Service;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Auth;
use app\common\logic\OrgLogic;
use fast\Random;
use think\Cache;
use think\Db;
use think\Exception;
use think\Validate;
use addons\third\model\Third;
use fast\Http;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['resetpwd','wxappLogin', 'login', 'visitor'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /*
   * 微信小程序登陆
   *  @param code rawData
   * */
   /* public function wxappLogin() {
        $config = config('wxapp');
        $code = $this->request->post("code");
        $org_cate_id = $this->request->post("org_cate_id");
        if (!$org_cate_id) {
            $this->error('请先选择单位，再登陆');
        }
        //单位必须为顶级
        (new OrgLogic())->check($org_cate_id);
        $rawData = $this->request->post("rawData", '', 'trim');
        if (!$code || !$rawData) {
            $this->error("参数不正确");
        }
        $userInfo = (array)json_decode($rawData, true);
        $params = [
            'appid'      => $config['app_id'],
            'secret'     => $config['app_secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');

        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                $platform = 'wxapp';
                $values = [
                    'platform'      => $platform,
                    'openid'        => $json['openid'],
                    'openname'      => isset($userInfo['nickName']) ? $userInfo['nickName'] : '',
                    'access_token'  => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                    'logintime'     => time(),
                    'expiretime'    => time() + (isset($json['expires_in']) ? $json['expires_in'] : 0),
                    'avatar' => $userInfo['avatarUrl'],
                    'gender' => $userInfo['gender']
                ];
                $extend = ['gender' => $userInfo['gender'], 'nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl']];
                //把用户的信息微信登陆信息存储刀session 完全登陆之后 删除该session
                Cache::set($json['openid'],json_encode([
                    'values' => $values,
                    'extend' => $extend
                ]),3600);

                $this->success('授权成功', ['org_cate_id' => $org_cate_id, 'open_id' => $json['openid']]);
            } else {
                $this->error("登录失败");
            }
        }

        return;
    }*/


    public function wxappLogin() {
//        $config = config('wxapp');
        $config = config('config')['epay']['wechat'];
        $code = $this->request->post("code");
        $rawData = $this->request->post("rawData", '', 'trim');
        $org_cate_id = $this->request->post('org_cate_id'); //所属单位
        if (!$code || !$rawData) {
            $this->error("参数不正确");
        }
        $userInfo = (array)json_decode($rawData, true);
        $params = [
            'appid'      => $config['app_id'],
            'secret'     => $config['app_secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                $platform = 'wxapp';
                $values = [
                    'platform'      => $platform,
                    'openid'        => $json['openid'],
                    'openname'      => isset($userInfo['nickName']) ? $userInfo['nickName'] : '',
                    'access_token'  => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                    'logintime'     => time(),
                    'expiretime'    => time() + (isset($json['expires_in']) ? $json['expires_in'] : 0),
                    'avatar' => $userInfo['avatarUrl'],
                    'gender' => $userInfo['gender']
                ];
                $extend = ['gender' => $userInfo['gender'], 'nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl']];
                //把用户的信息微信登陆信息存储刀session 完全登陆之后 删除该session
                Cache::set($json['openid'],json_encode([
                    'values' => $values,
                    'extend' => $extend
                ]),3600);
//                $this->visitor($json['openid'], $org_cate_id);
                $sessionInfo = Cache::get($json['openid']);
                $sessionInfo = json_decode($sessionInfo, true);
                if (!$org_cate_id) {
                    $this->error('请先选择单位，再登陆');
                }
                //单位必须为顶级
                (new OrgLogic())->check($org_cate_id);
                if (!$sessionInfo) {
                    $this->error("微信未授权不能登陆", null, -2);
                }
                $values = $sessionInfo['values'];
//        $platform = 'wxapp_visitor';
                $platform = 'wxapp';
//        $third = Third::get(['platform' => 'wxapp', 'openid' => $values['openid']]);
//        if ($third) {
//            $this->error('该微信已绑定账号，请用绑定账号登陆');
//        }
                $result = [
                    'openid'        => $values['openid'],
                    'userinfo'      => [
                        'nickname' => $values['openname'],
                    ],
                    'access_token'  => $values['access_token'],
                    'refresh_token' => '',
                    'expires_in'    => isset($values['expires_in']) ? $values['expires_in'] : 0,
                    'org_cate_id'=>$org_cate_id
                ];
                $extend = ['gender' => $values['gender'], 'nickname' => $values['openname'], 'avatar' => $values['avatar']];

                $ret = Service::connect($platform, $result, $extend,0);
                if ($ret) {
                    $auth = Auth::instance();
                    Db::startTrans();
                    try {
                        //更新用户信息
                        $data['openid'] = $values['openid'];
                        $data['org_cate_id'] = $org_cate_id;
                        $data['logintime'] = time();
                        Db::name('org_cate_history')->insert($data);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    $this->success("登录成功", ['userinfo' => $auth->getUserinfo()]);
                } else {
                    $this->error("连接失败");
                }
//                $this->success('授权成功', ['open_id' => $json['openid']]);
            } else {
                $this->error("登录失败");
            }
        }

        return;
    }
    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        $platform = $this->request->request('platform', 'wxapp');
        $org_cate_id = $this->request->request('org_cate_id'); //所属单位
        $open_id = $this->request->request('open_id');
        if (!$org_cate_id) {
            $this->error('请先选择单位，再登陆');
        }
        $sessionInfo = Cache::get($open_id);
        $sessionInfo = json_decode($sessionInfo, true);
        //单位必须为顶级
        $orgLogic = new OrgLogic();
        $orgLogic->check($org_cate_id);
        if (!$account || !$password || !$platform) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            //登陆成功后把第三方登陆信息
            $userinfo = $this->auth->getUserinfo();
            if ($sessionInfo) {
                $one = $orgLogic->getOneLevel($userinfo['org_cate_id']);
                if ($one['id'] != $org_cate_id) {
                    $this->error('账号无权登陆该单位，请正确选择单位');
                }
                $values = $sessionInfo['values'];
                //session信息存在的情况下 如果第三方信息未记录 那么就创建 如果已经记录那就更新
                //判断是否游客登录账号
                $third_visitor = Third::get(['platform' => 'wxapp_visitor', 'openid' => $values['openid']]);
                if($third_visitor){
                    $old_user_id = $third_visitor['user_id'];
                    Db::name('third')->where('id', $third_visitor['id'])->update(['user_id'=>$userinfo['id'], 'platform'=>$values['platform']]);
                    Db::name('learn_course_order')->where('user_id', $old_user_id)->update(['user_id'=>$userinfo['id']]);
                    Db::name('consult_reply')->where('user_id', $old_user_id)->update(['user_id'=>$userinfo['id']]);
                    Db::name('coupon_user')->where('user_id', $old_user_id)->update(['user_id'=>$userinfo['id']]);
                    Db::name('parent_questions')->where('user_id', $old_user_id)->update(['user_id'=>$userinfo['id']]);
                    Db::name('parent_answers')->where('user_id', $old_user_id)->update(['user_id'=>$userinfo['id']]);
                }
                $third = Third::get(['platform' => $values['platform'], 'openid' => $values['openid']]);
                if ($third) {
                    $user = \app\common\model\User::get($third['user_id']);
                    if (!$user || $user['id'] !== $userinfo['id']) {//微信账号和用户绑定
                        $this->error('该账户已经与微信绑定，请用绑定微信登陆');
                    }
                    $third->allowField(true)->save($values);
                } else {
                    // 保存第三方信息 用户user_id和第三方信息绑定
                    $values['user_id'] = $userinfo['id'];
                    (new Third($values))->allowField(true)->save();
                }
                //更新用户信息
                $user = $this->auth->getUser();
                $user->nickname = $values['openname'];
                $user->avatar = $values['avatar'];
                $user->gender = $values['gender'];
                $user->save();
            } else {
                //如果 授权session信息不存在  判断一下 之前是否授权过 如果没有授权过 就报错
                $third = Third::get(['platform' => $platform, 'user_id' =>$userinfo['id']]);
                if ($third) {
                    $this->error('请先微信授权', null, -2);
                }
            }
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 访客登陆
     * 访客每次登陆 都更新一下单位信息
     */
    public function visitor($open_id, $org_cate_id) {
//        $open_id = $this->request->request('open_id');
//        $org_cate_id = $this->request->request('org_cate_id'); //所属单位
        $sessionInfo = Cache::get($open_id);
        $sessionInfo = json_decode($sessionInfo, true);
        if (!$org_cate_id) {
            $this->error('请先选择单位，再登陆');
        }
        //单位必须为顶级
        (new OrgLogic())->check($org_cate_id);
        if (!$sessionInfo) {
            $this->error("微信未授权不能登陆", null, -2);
        }
        $values = $sessionInfo['values'];
//        $platform = 'wxapp_visitor';
        $platform = 'wxapp';
//        $third = Third::get(['platform' => 'wxapp', 'openid' => $values['openid']]);
//        if ($third) {
//            $this->error('该微信已绑定账号，请用绑定账号登陆');
//        }
        $result = [
            'openid'        => $values['openid'],
            'userinfo'      => [
                'nickname' => $values['openname'],
            ],
            'access_token'  => $values['access_token'],
            'refresh_token' => '',
            'expires_in'    => isset($values['expires_in']) ? $values['expires_in'] : 0,
        ];
        $extend = ['gender' => $values['gender'], 'nickname' => $values['openname'], 'avatar' => $values['avatar']];

        $ret = Service::connect($platform, $result, $extend,0);
        if ($ret) {
            $auth = Auth::instance();
            //更新用户信息
//            $user = $this->auth->getUser();
//            $user->org_cate_id = $org_cate_id;  //当前登陆单位
//            $user->user_type = 2;
//            $user->save();
            $this->success("登录成功", ['userinfo' => $auth->getUserinfo()]);
        } else {
            $this->error("连接失败");
        }
    }

    public function bindinfo()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        $platform = $this->request->request('platform', 'wxapp');
        $open_id = $this->request->request('open_id');
        $org_cate_id = $this->request->request('org_cate_id');
        if (!$org_cate_id) {
            $this->error('请先选择单位，再绑定');
        }
        //单位必须为顶级
        (new OrgLogic())->check($org_cate_id);
        if (!$account || !$password || !$platform) {
            $this->error(__('Invalid parameters'));
        }
        $bindthird = Third::get(UID);
        if($bindthird['u_id'] > 0){
            $this->error('该微信已经绑定账号，请勿重复绑定！');
            return false;
        }
        $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
        $user_mdl = new \app\common\model\User();
//        $user = $user_mdl::get([$field => $account]);
        $child = (new OrgLogic())->getCateChild($org_cate_id);
        $user = $user_mdl::get([$field => $account,'org_cate_id'=>['in', $child]]);
        if (!$user) {
            $this->error('账号错误！');
            return false;
        }
        if ($user->password !=$this->auth->getEncryptPassword($password, $user->salt)) {
            $this->error('密码错误！');
            return false;
        }
        $third = Third::get(['u_id' => $user->id]);
        if($third){
            $this->error('该账号已绑定微信，请勿重复绑定！');
            return false;
        }

        $info['u_id'] = $user->id;
        $info['username'] = $user->username;
        $info['password'] = $user->password;
        $info['mobile'] = $user->mobile;
        $info['user_type'] = $user->user_type;

        $res = Db::name('third')->where('id',UID)->update($info);
        if ($res) {
            $this->auth->direct(UID);
            $this->success(__('绑定成功！'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function unbindinfo()
    {
        $bindthird = Third::get(UID);
        if($bindthird['u_id'] <= 0){
            $this->error('账号没有绑定，请勿重复解绑！');
            return false;
        }
        $info['u_id'] = 0;
        $info['username'] = 'u' . UID;
        $password = Random::alnum(6);
        $info['password'] = md5(md5($password));
        $info['mobile'] = '';
        $info['user_type'] = 2;
        $res = Db::name('third')->where('id',UID)->update($info);
        if ($res) {
            $this->auth->direct(UID);
            $this->success(__('绑定成功！'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo() {
        $user = $this->auth->getUserinfo();
        $this->success('用户信息', $user);
    }

    public function scorechange()
    {
        $score = $this->request->request('score');
        $timelong = $this->request->request('timelong');
        $uid = Db::name('third')->where('id', UID)->value('u_id', 0);
        if($uid <= 0){
            $this->error('您还未绑定用户，请先绑定！');
        }
        Db::startTrans();
        try {
            Db::name('user')->where(['id' => $uid])->setInc('score', $score);
            Db::name('user')->where(['id' => $uid])->setInc('timelong', $timelong);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('积分和时长添加成功！');

    }



    //=======================================================================================

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }


    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $email   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }



    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }





}
